package servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.MessageDao;
import dao.TouristDao;
import model.Message;
import model.Tourist;

/**
 * Servlet implementation class addMessageServlet
 */
@WebServlet("/MessageServlet")
public class MessageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MessageServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// response.getWriter().append("Served at: ").append(request.getContextPath());
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		String handle = request.getParameter("handle");
		if (handle != null && handle.equals("addMessage")) {
			String messageWord = request.getParameter("message");
			String vname = request.getParameter("vname");
			 Date time= new java.sql.Date(new java.util.Date().getTime());
			 
			HttpSession session = request.getSession();
			Tourist tourist1 = (Tourist) session.getAttribute("tourist");
			try {
				Tourist tourist = TouristDao.getTouristNoCache(tourist1.getEmail());
				// tourist
				Message message = MessageDao.newMessage(tourist.getEmail(), vname);
				message.setTime(time);
				if (!MessageDao.getMessageNoCacheForBool(message)) {
					message.setInfo(messageWord);
					MessageDao.addMessage(message);
					String flag = "1";
					request.setAttribute("flag", flag);
					request.getRequestDispatcher("MessageList.jsp").forward(request, response);

				} else {

					String flag = "2";
					request.setAttribute("flag", flag);
					request.getRequestDispatcher("MessageList.jsp").forward(request, response);

				}
			} catch (Exception e) {
				String flag = "0";
				request.setAttribute("flag", flag);
				request.getRequestDispatcher("MessageList.jsp").forward(request, response);
				// e.printStackTrace();
			}

		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
